import { reactive, ref, computed, watch } from 'vue';
import { message } from 'ant-design-vue';
import { useTableData } from './useTableData';
import { useTableForm } from './useTableForm';
import { useTableSelection } from './useTableSelection';

/**
 * 表格CRUD操作的统一hook
 * 整合数据加载、表单操作、行选择、搜索功能
 * @param {Object} options - 配置选项
 * @returns {Object} - 返回CRUD相关状态和方法
 */
export function useTableCrud(options) {
  const {
    // API配置
    api = {
      list: null,
      add: null,
      update: null,
      delete: null,
      detail: null,
      batchDelete: null,
    }, 
    // 查询参数
    queryParams = {},
    // 分页配置
    pagination = true,
    // 默认表单数据
    defaultForm = {},
    // 表单验证规则
    formRules = {},
    // 默认查询参数
    defaultParams = {},
    // 行主键
    rowKey = 'id',
    // 是否自动刷新
    autoRefresh = true,
    // 数据转换
    transform = {
      request: null,
      response: null,
      form: null,
    },
    // 是否自动处理错误
    autoHandleError = true,
  } = options || {};

  // 使用子hooks
  const tableData = useTableData({
    queryParams,
    fetchApi: api.list,
    defaultParams,
    pagination,
    immediate: true,
    transformResponse: transform.response,
    autoHandleError,
  });

  const tableForm = useTableForm({
    defaultForm,
    rules: formRules,
    addApi: api.add,
    updateApi: api.update,
    getDetailApi: api.detail,
    transform: transform.form,
    autoHandleError,
    afterSubmit: () => {
      if (autoRefresh) {
        tableData.refreshData();
      }
    },
  });

  const tableSelection = useTableSelection({
    rowKey,
    dataSource: computed(() => tableData.dataList),
  });

  // 删除操作
  const handleDelete = async (record) => {
    debugger
    if (!api.delete) {
      message.error('未配置删除接口');
      return;
    }
    
    try {      
      const id = typeof rowKey === 'function' ? rowKey(record) : record[rowKey];
      const response = await api.delete({id});
      
      message.success('删除成功');
      
      // 刷新数据
      if (autoRefresh) {
        tableData.refreshData();
      }
      
      return response;
    } catch (err) {
      if (autoHandleError) {
        message.error(err.message || '删除失败');
      }
      throw err;
    }
  };

  // 批量删除操作
  const handleBatchDelete = async () => {
    if (!api.batchDelete && !api.delete) {
      message.error('未配置批量删除接口');
      return;
    }
    
    if (tableSelection.selectedRowKeys.value.length === 0) {
      message.warning('请选择要删除的项');
      return;
    }
    
    try {
      let response;
      
      // 使用批量删除接口
      if (api.batchDelete) {
        response = await api.batchDelete(tableSelection.selectedRowKeys.value);
      } else {
        // 使用单个删除接口逐个删除
        const promises = tableSelection.selectedRowKeys.value.map(id => api.delete(id));
        response = await Promise.all(promises);
      }
      
      message.success('批量删除成功');
      
      // 清空选择
      tableSelection.clearSelection();
      
      // 刷新数据
      if (autoRefresh) {
        tableData.refreshData();
      }
      
      return response;
    } catch (err) {
      if (autoHandleError) {
        message.error(err.message || '批量删除失败');
      }
      throw err;
    }
  };

  // 添加操作
  const handleAdd = () => {
    tableForm.openForm(null);
  };

  // 编辑操作
  const handleEdit = (record) => {
    tableForm.openForm(record);
  };

  //查询操作
  const handleSearch = (params) => {
    tableData.loadData();
  };

  //重置操作
  const handleReset = () => {
    // 清空查询参数的所有属性值，但保留对象引用
    Object.keys(queryParams).forEach(key => {
      queryParams[key] = undefined;
    });
    // 重置后重新加载数据
    tableData.loadData();
  };
 
  

  return {
    // 子hooks
    tableData,
    tableForm,
    tableSelection,
    modalVisible: tableForm.modalVisible,
    modalTitle: tableForm.modalTitle,
    
    // 便捷访问常用状态
    dataList: tableData.dataList,
    loading: tableData.loading,
    handleTableChange:tableData.handleTableChange,
    loadData: tableData.loadData,
    queryParams: queryParams,
    pagination: tableData.pagination,
    formState: tableForm.formState,
    selectedRowKeys: tableSelection.selectedRowKeys,
    selectedRows: tableSelection.selectedRows,
    
    // CRUD方法
    handleAdd,
    handleEdit,
    handleDelete,
    handleBatchDelete,
    
    // 便捷访问常用方法
    refreshData: tableData.refreshData,
    submitForm: tableForm.submitForm,
    resetForm: tableForm.resetForm,
    handleSearch,
    handleReset,
    clearSelection: tableSelection.clearSelection,
  };
}
